package Test1;

import java.util.ArrayList;

public class TestDemo10 {
    public static void main(String[] args) {

    }
    public ArrayList<Integer> spiralOrder (int[][] matrix) {
        // write code here
        ArrayList<Integer> arrayList = new ArrayList<>();
        if(matrix == null || matrix.length == 0) return arrayList;
        int up = 0;   //上边界
        int down = matrix.length-1;   //下边界
        int left = 0;   //左
        int right = matrix[0].length-1;   //右边界
        while (left <= right && up <= down) {
            for (int i = left; i <= right; i++) {
                arrayList.add(matrix[up][i]);
            }
            up++;
            if(up>down) break;
            for (int i = up; i <= down ; i++) {
                arrayList.add(matrix[i][right]);
            }
            right--;
            if(left>right) break;
            for (int i = right; i >= left ; i--) {
                arrayList.add(matrix[down][i]);
            }
            down--;
            if(up>down) break;
            for (int i = down; i >= up  ; i--) {
                arrayList.add(matrix[i][left]);
            }
            left++;
            if(left>right) break;
        }
        return arrayList;
    }
}
